﻿using System.Reflection;

namespace NGridDrawer.Components
{
    /// <LastUpdate author="Blaise Braye" Date="30/06/2008 13:22"/>
    /// <summary>
    /// this static class contains methods which are reflection helpers
    /// </summary>
    public static class PropHelper
    {
        /// <summary>
        /// Copy a property existing in type T from source to target
        /// </summary>
        /// <param name="source">source object
        /// </param>
        /// <param name="target">target object
        /// </param>
        /// <param name="propertyName">name of the property to copy (its value) from source to target
        /// </param>
        public static void CopyProperty<T>(T source, T target, string propertyName)
        {
            PropertyInfo prop = typeof (T).GetProperty(propertyName);
            if (prop != null && prop.GetSetMethod() != null)
            {
                object value = prop.GetValue(source, null);
                prop.SetValue(target, value, null);
            }
        }

        /// <summary>
        /// Copy a properties existing in type T from source to target
        /// </summary>
        /// <param name="source">source object
        /// </param>
        /// <param name="target">target object
        /// </param>
        public static void MovePropertiesTo<T>(T source, T target)
        {
            if (!source.Equals(target))
            {
                foreach (PropertyInfo prop in typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance))
                {
                    if (prop.GetSetMethod() != null)
                    {
                        object sourceValue = prop.GetValue(source, null);
                        prop.SetValue(target, sourceValue, null);
                    }
                }
            }
        }


        /// <summary>
        /// Check if type T contains the property named "<paramref name="propertyName"/>" value
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="propertyName">name of the property to search in type T
        /// </param>
        /// <returns>Contains the given property
        /// </returns>
        public static bool ContainsProp<T>(T obj, string propertyName)
        {
            return obj.GetType().GetProperty(propertyName) != null;
        }
    }
}